﻿using System;
using System.Data;
using BLL;
using DAL;
using Ext.Net;

namespace ERP.Modules
{
    public partial class Report_Expenditure : System.Web.UI.UserControl
    {
        #region[Define]
        private static bool _flag;
        #endregion

        #region[Controller]
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!X.IsAjaxRequest)
            {
                GetReportExpenditure();
                btnChooseExpenditure.Disable(true);
                btnEdit.Disable(true);
                btnDel.Disable(true);
                btnExport.Disable(true);
            }
        }
        //Store
        protected void StoreReportExpenditure_RefreshData(object sender, StoreReadDataEventArgs e)
        {
            txtDateBeginFillter.Text = string.Empty;
            txtDateBeginFillter.Text = string.Empty;
            GetReportExpenditure();
        }
        protected void StoreReportExpenditure_Detail_RefreshData(object sender, StoreReadDataEventArgs e)
        {
            if (String.IsNullOrEmpty(txtReportExpenditure_ID.Text))
            {
                GetReportExpenditureReportDetailTemp();
            }
            else
            {
                if (_flag)
                {
                    GetReportExpenditureReportDetailTemp();
                    GetReportExpenditureReportDetailTempSum();
                }
                else
                {
                    GetReportExpenditureReportDetail(int.Parse(txtReportExpenditure_ID.Text));
                    GetReportExpenditureReportDetailSum(int.Parse(txtReportExpenditure_ID.Text));
                }
            }
        }
        protected void StoreReportExpenditureOrder_RefreshData(object sender, StoreReadDataEventArgs e)
        {
            txtDateBeginExpenditureFillter.Text = string.Empty;
            txtDateEndExpenditureFillter.Text = string.Empty;
            GetExpenditure();
        }
        //Button
        protected void btnAddNew_Click(object sender, DirectEventArgs e)
        {
            _flag = true;
            GetAutoID();
            ClearText();
            btnRefreshReportExpenditureCode.Enable(true);
            btnSavePopUp.Enable(true);
            btnAddMaterial.Enable(true);
            btnDelMaterial.Enable(true);
            var obj = new EtReportExpenditureDetail { Users_Id = int.Parse(Session["Users_Id"].ToString()) };
            BllReportExpenditure.DeleteTempAdd(obj);
            WindowsReportExpenditure.Show();
        }
        protected void btnEdit_Click(object sender, DirectEventArgs e)
        {
            var sm = grReportExpenditure.GetSelectionModel() as CheckboxSelectionModel;
            if (sm != null)
                foreach (var row in sm.SelectedRows)
                {
                    _flag = false;
                    txtReason.Text = string.Empty;
                    txtReportExpenditureCode.ReadOnly = true;
                    btnRefreshReportExpenditureCode.Disable(true);
                    btnAddMaterial.Disable(true);
                    GetReportRceiptEdit(int.Parse(row.RecordID));
                    GetReportExpenditureReportDetail(int.Parse(row.RecordID));
                    GetReportExpenditureReportDetailSum(int.Parse(row.RecordID));
                    WindowsReportExpenditure.Show();
                }
        }
        protected void btnDel_Click(object sender, DirectEventArgs e)
        {
            var sm = grReportExpenditure.GetSelectionModel() as CheckboxSelectionModel;
            if (sm != null)
                foreach (var row in sm.SelectedRows)
                {
                    try
                    {
                        var obj = new EtReportExpenditure
                        {
                            ReportExpenditure_ID = int.Parse(row.RecordID),
                        };
                        BllReportExpenditure.Delete(obj);
                        if (obj.Msg == 0)
                            HTML.clsFormat.Alert_ERROR("Thông Báo", "Tồn tại chứng từ, không xoá được vui lòng xoá chứng từ trước !");
                    }
                    catch (Exception)
                    {
                        HTML.clsFormat.Alert_ERROR("Thông Báo", "Tồn tại tài liệu con, không xoá được vui lòng xoá tài liệu con trước !");
                    }
                }
            GetReportExpenditure();
        }
        protected void btnFillter_Click(object sender, DirectEventArgs e)
        {
            GetExpenditureFillterDateMain();
        }
        protected void btnSavePopUp_Click(object sender, DirectEventArgs e)
        {
            Insert();
        }
        protected void btnAddMaterial_Click(object sender, DirectEventArgs e)
        {
            var sm = grExpenditure.GetSelectionModel() as CheckboxSelectionModel;
            if (sm != null) sm.DeselectAll();
            GetExpenditure();
            WindowExpenditure.Show();
        }
        protected void btnDelMaterial_Click(object sender, DirectEventArgs e)
        {
            var sm = grReportExpenditure_Detail.GetSelectionModel() as CheckboxSelectionModel;
            var gridParam = e.ExtraParams["grReportExpenditure_Detail"];
            var _dtGrid = JSON.Deserialize<DataTable>(gridParam);
            if (_dtGrid != null && _dtGrid.Rows.Count > 0)
            {
                foreach (DataRow rows in _dtGrid.Rows)
                {
                    if (sm != null)
                        foreach (var row in sm.SelectedRows)
                        {
                            try
                            {
                                if (_flag)
                                {
                                    var obj = new EtReportExpenditureDetail
                                    {
                                        ReportDetail_Id = int.Parse(row.RecordID),
                                        Expenditure_ID = int.Parse(rows["Expenditure_ID"].ToString())
                                    };
                                    BllReportExpenditure.DeleteTemp(obj);
                                }
                                else
                                {
                                    var obj = new EtReportExpenditureDetail
                                    {
                                        ReportDetail_Id = int.Parse(row.RecordID),
                                        Expenditure_ID = int.Parse(rows["Expenditure_ID"].ToString()),
                                        Users_Id = int.Parse(Session["Users_Id"].ToString()),
                                        ReportExpenditure_ID = int.Parse(txtReportExpenditure_ID.Text),
                                        Reason = txtReason.Text
                                    };
                                    BllReportExpenditure.DeleteDetail(obj);
                                }
                            }
                            catch (Exception ex)
                            {
                                HTML.clsFormat.Alert_ERROR("Thông Báo", ex.Message);
                            }
                        }
                }
                GetReportExpenditureReportDetailTemp();
                GetReportExpenditureReportDetailTempSum();
                GetReportExpenditureReportDetail(int.Parse(txtReportExpenditure_ID.Text));
                GetReportExpenditureReportDetailSum(int.Parse(txtReportExpenditure_ID.Text));
            }
        }
        protected void btnCancelPopUp_Click(object sender, DirectEventArgs e)
        {
            WindowsReportExpenditure.Close();
        }
        protected void btnRefreshReportExpenditureCode_Click(object sender, DirectEventArgs e)
        {
            GetAutoID();
        }
        protected void btnChooseExpenditure_Click(object sender, DirectEventArgs e)
        {
            InsertDetail();
        }
        protected void btnReportFillterReport_Click(object sender, DirectEventArgs e)
        {
            GetExpenditureFillterDate();
        }
        //Double-Click
        protected void ReportExpenditureDblClick(object sender, DirectEventArgs e)
        {
            _flag = false;
            txtReason.Text = string.Empty;
            txtReportExpenditureCode.ReadOnly = true;
            btnRefreshReportExpenditureCode.Disable(true);
            btnAddMaterial.Disable(true);
            int ReportExpenditure_ID = int.Parse(e.ExtraParams["ReportExpenditure_ID"]);
            GetReportRceiptEdit(ReportExpenditure_ID);
            GetReportExpenditureReportDetail(ReportExpenditure_ID);
            GetReportExpenditureReportDetailSum(ReportExpenditure_ID);
            WindowsReportExpenditure.Show();
        }
        protected void ReportExpenditureDetailDblClick(object sender, DirectEventArgs e)
        {

        }
        //Search
        protected void Search_Event(object sender, DirectEventArgs e)
        {

        }
        //Menu
        protected void MenuItemExportExcel_Click(object sender, DirectEventArgs e)
        {

        }
        #endregion

        #region[Method]
        private void GetReportExpenditure()
        {
            var _clsGetReport = new BllReportExpenditure();
            var _dtGetReport = _clsGetReport.GetReportExpenditure(txtSearch.Text);
            if (_dtGetReport != null && _dtGetReport.Rows.Count > 0)
            {
                StoreReportExpenditure.DataSource = _dtGetReport;
                StoreReportExpenditure.DataBind();
            }
            else
            {
                grReportExpenditure.GetStore().RemoveAll();
            }
        }
        private void GetReportRceiptEdit(int id)
        {
            var _clsGetReportEdit = new BllReportExpenditure();
            var _dtGetReportEdit = _clsGetReportEdit.GetReportExpenditureEdit(id);
            if (_dtGetReportEdit != null && _dtGetReportEdit.Rows.Count > 0)
            {
                txtReportExpenditure_ID.Text = _dtGetReportEdit.Rows[0]["ReportExpenditure_ID"].ToString();
                txtReportExpenditureCode.Text = _dtGetReportEdit.Rows[0]["ReportExpenditure_Code"].ToString();
                txtAmount_Total.Text = String.Format("{0:0,00}", _dtGetReportEdit.Rows[0]["Amount_Total"]).Replace(".", ",");
                txtDateBegin.Text = _dtGetReportEdit.Rows[0]["DateCreate"].ToString();
                txtNote.Text = _dtGetReportEdit.Rows[0]["Note"].ToString();
            }
        }
        private void GetReportExpenditureReportDetailTemp()
        {
            var _clsGetReportDetailTemp = new BllReportExpenditure();
            var _dtGetReportDetailTemp =
                _clsGetReportDetailTemp.GetReportExpenditureDetailTemp(int.Parse(Session["Users_Id"].ToString()));
            if (_dtGetReportDetailTemp != null && _dtGetReportDetailTemp.Rows.Count > 0)
            {
                StoreReportExpenditure_Detail.DataSource = _dtGetReportDetailTemp;
                StoreReportExpenditure_Detail.DataBind();
            }
            else
            {
                grReportExpenditure_Detail.GetStore().RemoveAll();
            }
        }
        private void GetReportExpenditureReportDetailTempSum()
        {
            var _clsGetReportDetailTempSum = new BllReportExpenditure();
            var _dtGetReportDetailTempSum =
                _clsGetReportDetailTempSum.GetReportExpenditureDetailTempSum(int.Parse(Session["Users_Id"].ToString()));
            if (_dtGetReportDetailTempSum != null && _dtGetReportDetailTempSum.Rows.Count > 0)
            {
                txtAmount_Total.Text = String.Format("{0:0,00}", _dtGetReportDetailTempSum.Rows[0]["Toal_Amount"]).Replace(".", ",");
                lbPriVATOrderReportExpenditure.Text = String.Format("{0:0,00}", _dtGetReportDetailTempSum.Rows[0]["Total_VoucherAmount"]).Replace(".", ",");
                lbTotalCostOrderReportExpenditure.Text = String.Format("{0:0,00}", _dtGetReportDetailTempSum.Rows[0]["Toal_Amount"]).Replace(".", ",");
            }
        }
        private void GetReportExpenditureReportDetail(int id)
        {
            var _clsGetReportDetail = new BllReportExpenditure();
            var _dtGetReportDetail = _clsGetReportDetail.GetReportExpenditureDetail(id);
            if (_dtGetReportDetail != null && _dtGetReportDetail.Rows.Count > 0)
            {
                StoreReportExpenditure_Detail.DataSource = _dtGetReportDetail;
                StoreReportExpenditure_Detail.DataBind();
            }
            else
            {
                grReportExpenditure_Detail.GetStore().RemoveAll();
            }
        }
        private void GetReportExpenditureReportDetailSum(int id)
        {
            var _clsGetReportDetailSum = new BllReportExpenditure();
            var _dtGetReportDetailSum =
                _clsGetReportDetailSum.GetReportExpenditureDetailSum(id);
            if (_dtGetReportDetailSum != null && _dtGetReportDetailSum.Rows.Count > 0)
            {
                txtAmount_Total.Text = String.Format("{0:0,00}", _dtGetReportDetailSum.Rows[0]["Toal_Amount"]).Replace(".", ",");
                lbPriVATOrderReportExpenditure.Text = String.Format("{0:0,00}", _dtGetReportDetailSum.Rows[0]["Total_VoucherAmount"]).Replace(".", ",");
                lbTotalCostOrderReportExpenditure.Text = String.Format("{0:0,00}", _dtGetReportDetailSum.Rows[0]["Toal_Amount"]).Replace(".", ",");
            }
        }
        private void GetExpenditureFillterDate()
        {
            try
            {
                var _clsExpenditure = new BllExpenditure();
                if (String.IsNullOrEmpty(txtDateBeginExpenditureFillter.Text) && String.IsNullOrEmpty(txtDateEndExpenditureFillter.Text))
                {
                    var _dtGetExpenditure = _clsExpenditure.GetExpenditureReport(txtSearch.Text);
                    if (_dtGetExpenditure != null && _dtGetExpenditure.Rows.Count > 0)
                    {
                        StoreReportExpenditureOrder.DataSource = _dtGetExpenditure;
                        StoreReportExpenditureOrder.DataBind();
                    }
                    else
                    {
                        grExpenditure.GetStore().RemoveAll();
                    }
                }
                else
                {
                    var _dtGetExpenditure = _clsExpenditure.GetExpenditureReportFillterDate(txtDateBeginExpenditureFillter.Text, txtDateEndExpenditureFillter.Text);
                    if (_dtGetExpenditure != null && _dtGetExpenditure.Rows.Count > 0)
                    {
                        StoreReportExpenditureOrder.DataSource = _dtGetExpenditure;
                        StoreReportExpenditureOrder.DataBind();
                    }
                    else
                    {
                        grExpenditure.GetStore().RemoveAll();
                    }
                }
            }
            catch (Exception ex)
            {
                HTML.clsFormat.Alert_ERROR("Lỗi", "Có lỗi xảy ra trong quá trình lọc dữ liệu <br/>" + ex.Message);
            }
        }
        private void GetExpenditureFillterDateMain()
        {
            try
            {
                var _clsExpenditure = new BllReportExpenditure();
                if (String.IsNullOrEmpty(txtDateBeginFillter.Text) && String.IsNullOrEmpty(txtDateEndFillter.Text))
                {
                    var _dtGetExpenditure = _clsExpenditure.GetReportExpenditure(txtSearch.Text);
                    if (_dtGetExpenditure != null && _dtGetExpenditure.Rows.Count > 0)
                    {
                        StoreReportExpenditure.DataSource = _dtGetExpenditure;
                        StoreReportExpenditure.DataBind();
                    }
                    else
                    {
                        grReportExpenditure.GetStore().RemoveAll();
                    }
                }
                else
                {
                    var _dtGetExpenditureFillter = _clsExpenditure.GetReportExpenditureFillter(txtDateBeginFillter.Text, txtDateEndFillter.Text);
                    if (_dtGetExpenditureFillter != null && _dtGetExpenditureFillter.Rows.Count > 0)
                    {
                        StoreReportExpenditure.DataSource = _dtGetExpenditureFillter;
                        StoreReportExpenditure.DataBind();
                    }
                    else
                    {
                        grReportExpenditure.GetStore().RemoveAll();
                    }
                }
            }
            catch (Exception ex)
            {
                HTML.clsFormat.Alert_ERROR("Lỗi", "Có lỗi xảy ra trong quá trình lọc dữ liệu <br/>" + ex.Message);
            }
        }
        private void GetExpenditure()
        {
            var _clsExpenditure = new BllExpenditure();
            var _dtExpenditure = _clsExpenditure.GetExpenditureReport(string.Empty);
            if (_dtExpenditure != null && _dtExpenditure.Rows.Count > 0)
            {
                StoreReportExpenditureOrder.DataSource = _dtExpenditure;
                StoreReportExpenditureOrder.DataBind();
            }
            else
            {
                grExpenditure.GetStore().RemoveAll();
            }
        }
        private void GetAutoID()
        {
            var _clsCreateCode = new BllCreateCode();
            var _dtGetAutoID = _clsCreateCode.GetAutoID("ReportExpenditure_Code", "Report_Expenditure");
            if (_dtGetAutoID != null && _dtGetAutoID.Rows.Count > 0)
            {
                try
                {
                    txtReportExpenditureCode.Text = "BC.0000" +
                                      Convert.ToString(int.Parse(_dtGetAutoID.Rows[0]["Auto_ID"].ToString()) +
                                                       int.Parse(1.ToString()));
                }
                catch (Exception ex)
                {
                    HTML.clsFormat.Alert_ERROR("Thông Báo", ex.Message);
                }
            }
        }
        private bool CheckInsert()
        {
            var check = false;
            var _clsCheck = new BllReportExpenditure();
            var dtCheck = _clsCheck.GetReportExpenditure(string.Empty);
            if (dtCheck != null && dtCheck.Rows.Count > 0)
            {
                foreach (DataRow dr in dtCheck.Rows)
                {
                    if (txtReportExpenditure_ID.Text != dr["ReportExpenditure_ID"].ToString())
                    {
                        if (txtReportExpenditureCode.Text == dr["ReportExpenditure_Code"].ToString())
                        {
                            check = true;
                            HTML.clsFormat.Alert_ERROR("Thông Báo", "Mã báo cáo này đã tồn tại !");
                        }
                    }
                }
            }
            return check;
        }
        private void Insert()
        {
            if (_flag)
            {
                InsertValue();
            }
            else
            {
                UpdateValue();
            }
        }
        private void InsertValue()
        {
            try
            {
                if (!CheckInsert())
                {
                    var _clsGetReportDetailTempCheck = new BllReportExpenditure();
                    var _dtGetReportDetailTempCheck =
                        _clsGetReportDetailTempCheck.GetReportExpenditureDetailTemp(int.Parse(Session["Users_Id"].ToString()));
                    if (_dtGetReportDetailTempCheck.Rows.Count > 0)
                    {
                        var obj = new EtReportExpenditure
                        {
                            ReportExpenditure_Code = txtReportExpenditureCode.Text,
                            Amount_Total = float.Parse(txtAmount_Total.Text.Replace(",", "").Replace(".", "")),
                            DateCreate = DateTime.Parse(txtDateBegin.Text),
                            Note = txtNote.Text,
                            Lock = true
                        };
                        BllReportExpenditure.Insert(obj);
                        HTML.clsFormat.Alert_INFO("Thông Báo", "Chốt sổ thành công !");
                        GetReportExpenditure();
                        GetReportExpenditureReportDetailTemp();
                        GetAutoID();
                        ClearText();
                    }
                    else
                    {
                        HTML.clsFormat.Alert_ERROR("Lỗi", "Vui lòng chốt sổ trước khi cập nhật chứng từ !");
                    }
                }

            }
            catch (Exception ex)
            {
                HTML.clsFormat.Alert_ERROR("Lỗi", ex.Message);
            }
        }
        private void UpdateValue()
        {
            try
            {
                if (!CheckInsert())
                {
                    var obj = new EtReportExpenditure
                    {
                        ReportExpenditure_ID = int.Parse(txtReportExpenditure_ID.Text),
                        Note = txtNote.Text
                    };
                    BllReportExpenditure.Update(obj);
                    HTML.clsFormat.Alert_INFO("Thông Báo", "Thay đổi thành thành công !");
                    GetReportExpenditure();
                }

            }
            catch (Exception ex)
            {
                HTML.clsFormat.Alert_ERROR("Lỗi", ex.Message);
            }
        }
        private void InsertDetail()
        {
            try
            {
                var sm = grExpenditure.GetSelectionModel() as CheckboxSelectionModel;
                if (sm != null)
                {
                    foreach (var row in sm.SelectedRows)
                    {
                        var obj = new EtReportExpenditureDetail
                        {
                            ReportExpenditure_ID = null,
                            Expenditure_ID = int.Parse(row.RecordID),
                            Lock = true,
                            flag = 1,
                            Users_Id = int.Parse(Session["Users_Id"].ToString())
                        };
                        BllReportExpenditure.InsertDetail(obj);
                        HTML.clsFormat.Alert_INFO("Thông Báo", "Thêm phiếu chi thành công !");
                        WindowExpenditure.Close();
                    }
                }
                GetReportExpenditureReportDetailTemp();
                GetReportExpenditureReportDetailTempSum();
            }
            catch (Exception ex)
            {
                HTML.clsFormat.Alert_ERROR("Lỗi", ex.Message);
            }
        }
        #endregion

        #region[Clear-Text]
        private void ClearText()
        {
            txtReportExpenditure_ID.Text = string.Empty;
            txtDateBegin.Text = DateTime.Now.ToString();
            txtAmount_Total.Text = "0";
            txtNote.Text = string.Empty;
            grReportExpenditure_Detail.GetStore().RemoveAll();
            lbPriVATOrderReportExpenditure.Text = string.Empty;
            lbTotalCostOrderReportExpenditure.Text = string.Empty;
        }
        #endregion
    }
}